#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include "InitAddr.hpp"

const std::string sep = ": ";
std::string defaultPath = "./dictionary.txt";

class Dict
{
public:
    Dict(const std::string &path = defaultPath)
        : _dict_path(path)
    {
    }

    bool LoadDict()
    {
        // 将数据从磁盘导到内存的哈希表中
        // 打开我们的词典源文件
        std::ifstream in(_dict_path);
        if (!in.is_open())
        {
            std::cout << "打开失败" << std::endl;
            exit(1);
        }

        // 将内容导入到我们的词典哈希表中
        //istream从我们的键盘中读取内容，将读取到的内容放在line之中
        //ifstream从我们指定的文件中读取，将我们读取到的内容放在line之中
        std::string line;
        while (getline(in, line))
        {
            auto pos = line.find(sep);
            if (pos == std::string::npos)
            {
                std::cout << "未查询到相关内容" << std::endl;
                continue;
            }

            std::string English = line.substr(0, pos);
            std::string Chinese = line.substr(pos + sep.size()); // 默认直接提取到结尾

            _dict.insert(std::make_pair(English, Chinese));
        }

        std::cout << "加载成功" << std::endl;
        in.close();
        return true;
    }

    std::string Translate(const std::string &word, InitAddr& client)
    {
        auto iter = _dict.find(word);
        if (iter == _dict.end())
        {
            return "none";
        }
        std::cout << "client.ip: " << client.ip() << " client port:" << client.port() << std::endl;
        return iter->second;
    }

    ~Dict()
    {
    }

private:
    std::string _dict_path; // 字典+文件名
    std::unordered_map<std::string, std::string> _dict;
};